package org.lgiavedoni.android.franq.core.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.util.implementation.ImplementationUtil;

public class ServiceManager {

	public static final ServiceManager inst = new ServiceManager();
	private final Map<String, Service> services = new HashMap<String, Service>();
	private static final String IMPLEMENTATIONS_KEY = "services";

	private ServiceManager() {
		for (Object obj : ImplementationUtil.initialize(ImplementationUtil.getImplementations(IMPLEMENTATIONS_KEY))) {
			services.put(((Service) obj).getServiceName().toLowerCase(), (Service) obj);
		}
	}

	public Service getService(String name) {
		return services.get(name.toLowerCase());
	}

	public final Collection<Service> getAllServices() {
		List<Service> servicesL = new ArrayList<Service>(services.values());
		Collections.sort(servicesL);
		return servicesL;
	}

	public void startServices() {
		for (Service service : ServiceManager.inst.getAllServices()) {
			try {
				if (service.isEnable())
					service.start();
			} catch (Exception e) {
				Logger.inst.error(e);
			}
		}
	}

}
